/*
* @(#)ListDmsDocumentAction.java
*
* Copyright (c) 2003 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
*/

package com.dcivision.dms.web;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.bean.DmsValidation;
import com.dcivision.dms.bean.MtmDocumentRelationship;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.DocumentValidateManager;
import com.dcivision.dms.core.RootOperationManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsRootDAObject;
import com.dcivision.dms.dao.MtmDocumentRelationshipDAObject;
import com.dcivision.framework.ApplicationContainer;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.dao.SysUserDefinedIndexDAObject;
import com.dcivision.framework.taglib.layout.PagePathTag;
import com.dcivision.framework.taglib.layout.PageTitleTag;
import com.dcivision.framework.web.AbstractListAction;
import com.dcivision.framework.web.AbstractSearchForm;


/**
 * <p>Class Name:       ListDmsDocumentAction.java    </p>
 * <p>Description:      The list action class for ListUserRecord.jsp</p>
 * @author              Zoe Shum
 * @company             DCIVision Limited
 * @creation date       01/08/2003
 * @version             $Revision: 1.54.2.10 $
 */
public class ListDmsDocumentAction extends AbstractListAction {

  public static final String REVISION = "$Revision: 1.54.2.10 $";


  /**
   *  Constructor - Creates a new instance of ListDmsDocumentAction and define the default listName.
   */
  public ListDmsDocumentAction() {
    super();
    this.setListName("dmsDocumentList");
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.dms.dao.DmsDocumentDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.DMS_PERSONAL_FOLDER);
  }

 /**
   * execute - Override the parent function.
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
      if (!Utility.isEmpty(request.getSession().getAttribute(org.apache.struts.Globals.MESSAGE_KEY))) {
      this.addMessage(request, (String) request.getSession().getAttribute(org.apache.struts.Globals.MESSAGE_KEY));
      request.getSession().removeAttribute(org.apache.struts.Globals.MESSAGE_KEY);
    }
    if (!Utility.isEmpty(request.getSession().getAttribute(org.apache.struts.Globals.ERROR_KEY))) {
      this.addError(request, (String) request.getSession().getAttribute(org.apache.struts.Globals.ERROR_KEY));
      request.getSession().removeAttribute(org.apache.struts.Globals.ERROR_KEY);
    }

    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);

    // Retrieve the default document profile settings.
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    docRetrievalManager.checkNSetDefaultProfileList(request);

    // before Entering PERSONAL folder, checking access right.
    boolean hasRight = this.checkPersonalFolderAccessRight(form, request);
    
    if(!hasRight) {
      this.addError(request, "errors.dms.have_no_permissionon_target_file");
      
      try {
        String tempRedirectURL ="/jsp/alert/ErrorMessage.jsp";
        RequestDispatcher rd = request.getRequestDispatcher(tempRedirectURL);
        rd.forward(request,response);
        return null;
      } catch (IOException exp) {
        log.error("Forward Error Occor", exp);
      }
    }
    
    return super.execute(mapping, form, request, response);
  }
  /**
   * getListData
   * 
   * Override the parent's function. Purpose in create the default personal folder when non-exists, and load the
   * dmsDocument list.
   * 
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  public void getListData(ActionMapping mapping, AbstractSearchForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = null;
    ListDmsDocumentForm docSearchForm = (ListDmsDocumentForm) form;
    DmsDocument documentRoot = null;
    try {
      conn = this.getConnection(request);
      DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
      RootOperationManager rootOperationManager = new RootOperationManager(sessionContainer, conn);

      if (docSearchForm.getParentID() == null || docSearchForm.getRootID() == null) {
        log.debug("Both parentID and rootID = null");

        Integer userID = sessionContainer.getUserRecordID();
        DmsRootDAObject rootDAO = new DmsRootDAObject(sessionContainer, conn);
        List rootList = rootDAO.getRootByOwnerIDAndType(userID, DmsRoot.PERSONAL_ROOT, GlobalConstant.RECORD_STATUS_ACTIVE);
        log.debug(" Both parentID and rootID = null, rootList size = " + rootList.size());
        DmsRoot rootPoint = null;
        if (rootList.size() == 0) {
          // Create default root for user without root point
          log.debug("no default root, going to create one");
          rootPoint = rootOperationManager.createDefaultPersonalRootPointForUser();
        } else {
          rootPoint = (DmsRoot)rootList.get(0);
        }
        log.debug("root Point = " + rootPoint.getID() + " root Name = "+rootPoint.getRootName());

        // Init the value
        documentRoot = docRetrievalManager.getRootFolderByRootID(rootPoint.getID());
        request.setAttribute("rootFolder", documentRoot);
        docSearchForm.setRootID(rootPoint.getID().toString());
        //if docSearchForm.getParentID() is null ,try to get parentID from session ,if Cookies is null then get documentRoot.getID()
        if(docSearchForm.getParentID() == null) {
          String folderTreeParentID = (String)request.getSession().getAttribute("folderTreeParentID") ;
          if (!Utility.isEmpty(folderTreeParentID)) {
            docSearchForm.setParentID(folderTreeParentID);
          } else {
            docSearchForm.setParentID(documentRoot.getID().toString());
          }
        } else {
          //set the parentID to session
          request.getSession().setAttribute("folderTreeParentID", docSearchForm.getParentID().toString());
        }
        log.debug("retrieve the list on parentID = "+docSearchForm.getParentID() + " rootID = "+docSearchForm.getRootID());
        rootDAO = null;
      } else {
        documentRoot = docRetrievalManager.getRootFolderByRootID(new Integer(docSearchForm.getRootID()));
        request.setAttribute("rootFolder", documentRoot);
      }

      // Retrieve the folder list for folder tree listing.
      List folderTreeList = docRetrievalManager.getFolderByParentIDRootID(documentRoot.getID(), new Integer(docSearchForm.getRootID()));
      request.setAttribute("folderTreeList", folderTreeList);

      // Get the location path.
      Integer parentID = new Integer(docSearchForm.getParentID());
      String path = docRetrievalManager.getLocationPath(parentID);
      request.setAttribute("location", path);

       // check any document profile of the system
      SysUserDefinedIndexDAObject sysUserDefinedIndexDAO = new SysUserDefinedIndexDAObject(sessionContainer, conn);
      List sysUDFList = sysUserDefinedIndexDAO.getListByStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
      request.setAttribute("sysUDFList",sysUDFList);

      // Call the super list function.
      super.getListData(mapping, docSearchForm, request, response);

      // Retrive the workflow relationship.
      List listDoc = (List)request.getAttribute(this.m_sListName);
      List listWorkflowRelation = new ArrayList();
      com.dcivision.workflow.dao.MtmWorkflowProgressSystemObjectDAObject mtmWfProgressSysObjDAO = new com.dcivision.workflow.dao.
        MtmWorkflowProgressSystemObjectDAObject(this.getSessionContainer(request), conn);
      com.dcivision.workflow.dao.WorkflowRecordDAObject workflowRecordDAO = new com.dcivision.workflow.dao.WorkflowRecordDAObject(this.getSessionContainer(
        request), conn);
      for (int i = 0; i < listDoc.size(); i++) {
        List tmpList =new ArrayList();
        if(DmsDocument.DOCUMENT_LINK.equals(((DmsDocument)listDoc.get(i)).getDocumentType())){
          if(!Utility.isEmpty(((DmsDocument)listDoc.get(i)).getID())){
            DmsDocument targetDoc = docRetrievalManager.getRelationshipTargetDocument(((DmsDocument)listDoc.get(i)).getID(),((DmsDocument)listDoc.get(i)).getDocumentType());
            if(targetDoc!=null){
              tmpList = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(listDoc.get(i).getClass().getName(), targetDoc.getID());
            }
          }
        }else{
          tmpList = mtmWfProgressSysObjDAO.getListByBeanClassNameObjectID(listDoc.get(i).getClass().getName(), ( (DmsDocument)listDoc.get(i)).getID());
        }

        List tmpRow = new ArrayList();
        listWorkflowRelation.add(i, tmpRow);
        for (int j = 0; j < tmpList.size(); j++) {
          com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject tmpObj = (com.dcivision.workflow.bean.MtmWorkflowProgressSystemObject)tmpList.get(j);
          com.dcivision.workflow.bean.WorkflowRecord wfRec = (com.dcivision.workflow.bean.WorkflowRecord)workflowRecordDAO.getObjectByTrackID(tmpObj.getTrackID());
          if (wfRec != null) {
            tmpRow.add(new Object[] {wfRec, tmpObj.getTrackID()});
          }
        }
      }
      request.setAttribute("workflowRelationshipList", listWorkflowRelation);
      mtmWfProgressSysObjDAO=null;
      workflowRecordDAO=null;

      // Retrive the workflow relationship. End

      this.commit(request);

      docRetrievalManager.release();
      rootOperationManager.release();

    } catch (ApplicationException appEx) {
      this.rollback(request);
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      this.rollback(request);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
      conn = null;
    }
  }

  /**
   *  Method deleteListData() - delete the item(s) from listing page
   *
   *  @param      mapping               ActionMapping from struts
   *  @param      form                  ActionForm from struts
   *  @param      request               HttpServletReuqest
   *  @param      respond               HttpServletRespond
   *  @return     void
   *  @throws     ApplicationException  Throws ApplicationException the deleteion failed
   *  @deprecated This method has deprecated.
   */
  public void deleteListData2(ActionMapping mapping, AbstractSearchForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentOperationManager docOperationManager = null;
    DocumentRetrievalManager docRetrievalManager = null;
    List relationshipList=new ArrayList();
    List indirectRelationDocumentList=new ArrayList();
    MtmDocumentRelationshipDAObject dmsMtmDocumentRelationshipDAO = new MtmDocumentRelationshipDAObject (sessionContainer, conn);
    ArrayList clipboardList = (ArrayList)request.getSession().getAttribute("DMS_CLIPBOARD");
    try {
      docOperationManager = new DocumentOperationManager(sessionContainer, conn);
      docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);

      String[] selectedID = form.getBasicSelectedID();
      for (int i = 0; i < selectedID.length; i++) {
        if (!Utility.isEmpty(selectedID[i])) {
          DmsDocument document = docRetrievalManager.getDocument(TextUtility.parseIntegerObj(selectedID[i]));
          if (DmsDocument.FOLDER_TYPE.equals(document.getDocumentType()) ||
              DmsDocument.COMPOUND_DOC_TYPE.equals(document.getDocumentType()) ||
              DmsDocument.PAPER_DOC_TYPE.equals(document.getDocumentType()) ||
              DmsDocument.EMAIL_DOC_TYPE.equals(document.getDocumentType()) ||
              DmsDocument.FORM_DOC_TYPE.equals(document.getDocumentType()) ||
              DmsDocument.FLOW_DOC_TYPE.equals(document.getDocumentType())) {
          } else {
            relationshipList=dmsMtmDocumentRelationshipDAO.getListByRelationIDRelationType(document.getID(),null);
            indirectRelationDocumentList=dmsMtmDocumentRelationshipDAO.getListByIDRelationType(document.getID(),null);
            if(relationshipList.size()>0){
              for(int n=0;n<relationshipList.size();n++){
                MtmDocumentRelationship relationshipObj = (MtmDocumentRelationship)relationshipList.get(n);
                relationshipObj.setRecordStatus(GlobalConstant.RECORD_STATUS_INACTIVE);
                dmsMtmDocumentRelationshipDAO.updateObject(relationshipObj);
              }
            }
           if(indirectRelationDocumentList.size()>0){
             for(int n=0;n<indirectRelationDocumentList.size();n++){
               MtmDocumentRelationship relationshipObj =(MtmDocumentRelationship)indirectRelationDocumentList.get(n);
               relationshipObj.setRecordStatus(GlobalConstant.RECORD_STATUS_INACTIVE);
               dmsMtmDocumentRelationshipDAO.updateObject(relationshipObj);
             }
           }
            docOperationManager.deleteDocument(document);
          }
          if(clipboardList!=null && clipboardList.contains(new Integer(selectedID[i]))){
            clipboardList.remove(new Integer(selectedID[i]));
          }
        }
      }
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error("Error in deletion", e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
      conn = null;
      sessionContainer = null;
      docOperationManager.release();
      docRetrievalManager.release();
      docOperationManager = null;
      docRetrievalManager = null;
    }
  }

  public void deleteListData(ActionMapping mapping, AbstractSearchForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    ApplicationContainer container = (ApplicationContainer)request.getSession().getServletContext().getAttribute(GlobalConstant.APPLICATION_CONTAINER_KEY);

    List clipboardList = (List)request.getSession().getAttribute("DMS_CLIPBOARD");
    String[] selectedID = form.getBasicSelectedID();
    selectedID = docValidateManager.validatorFilterDocID(selectedID);
    boolean isIgnoreDeleteShortcut = ((ListDmsDocumentForm)form).isIgnoreDeleteShortcut();

    //step 1: loop and validate tree node, add id to lstIdHasRight/lstIdMisRight/lstIdBeLocked
    for (int n=0; n<selectedID.length; n++) {
      Integer srcDocumentId = TextUtility.parseIntegerObj(selectedID[n]);
      DmsDocument sourceDocument = (DmsDocument)dmsDocumentDAO.getObjectByID(srcDocumentId);
      DmsValidation validation = docValidateManager.validateDeleteAction(sourceDocument, isIgnoreDeleteShortcut);

      //step 2: begin delete documents
      String cacheKey = "D"+sessionContainer.getSessionID()+""+System.currentTimeMillis();
      try {
        List deleteDocumentIds = validation.getLstIdAccept();
        //step 2.1: check and lock operation id to application cache
        boolean success = container.checkAndLockDocumentOperationID(cacheKey, deleteDocumentIds, "ACDIMU");
        if (!success) {
          this.addError(request, "errors.dms.fail_to_delete", docRetrievalManager.getLocationPath(srcDocumentId));
          this.addError(request, "errors.dms.cannot_edit_now");
        }else {
          //step 2.2: delete documents
          docOperationManager.deleteDocument(sourceDocument, validation);

          //step 2.3: message throws
          List lstIdHasRight = validation.getLstIdAccept();
          List lstIdMisRight = validation.getLstIdReject();
          List lstIdBeLocked = validation.getLstIdlocked();
          List lstIdBeDeleted = validation.getLstIdDeleted();
          List lstIdBeArchived = validation.getLstIdArchived();
          List lstIdRelatedShortcut = validation.getLstIdHaveRelationship();
          String locationPath = docRetrievalManager.getLocationPath(srcDocumentId);
          if (validation.isSuccess()) {
            this.addMessage(request, "dms.message.document_deleted_success", locationPath, String.valueOf(lstIdHasRight.size()));
          }else {
            this.addError(request, "errors.dms.fail_to_delete", locationPath);
            for (int i=0; i<lstIdMisRight.size(); i++) {
              this.addError(request,"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i)));
            }
            for (int i=0; i<lstIdBeLocked.size(); i++) {
              this.addError(request,"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i)));
            }
            for (int i=0; i<lstIdBeDeleted.size(); i++) {
              this.addError(request,"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i)));
            }
            for (int i=0; i<lstIdBeArchived.size(); i++) {
              this.addError(request,"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i)));
            }
            for (int i=0; i<lstIdRelatedShortcut.size(); i++) {
              this.addError(request,"errors.dms.has_relationship",docRetrievalManager.getLocationPath((Integer)lstIdRelatedShortcut.get(i)));
            }
            }


          //step 2.4: delete from clipboard if it present
          if (clipboardList!=null && !clipboardList.isEmpty()) {
            for (int i=0; i<clipboardList.size(); i++) {
              if(deleteDocumentIds.contains(clipboardList.get(i))) {
                clipboardList.remove(i--);
              }
            }
          }
        }
      }catch (ApplicationException ex) {
        throw ex;
      }catch (Exception ex) {
        throw new ApplicationException(ex);
      }finally {
        container.unlockDmsDocumentOperationID(cacheKey);
      }
    }
    form.setBasicSelectedID(null);
    request.getSession().setAttribute("DMS_CLIPBOARD", clipboardList);
    form.setNavMode(GlobalConstant.NAV_MODE_VIEW);
    conn = null;
    sessionContainer = null;
    container = null;
    docValidateManager.release();
    docOperationManager.release();
    docRetrievalManager.release();
  }
  
  public void setPageTitle(HttpServletRequest request, HttpServletResponse response, ActionForm form, ActionMapping mapping,
      ActionForward actionForward) throws NumberFormatException, ApplicationException {
    super.setPageTitle(request, response, form, mapping, actionForward);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(getSessionContainer(request), getConnection(request));
    ListDmsDocumentForm listForm = (ListDmsDocumentForm) form;
    Integer folderID = Integer.valueOf(listForm.getParentID());
    DmsDocument currentFolder = docRetrievalManager.getDocument(folderID);
    
    final String pathSeparator = " " + File.separator + " ";
    
    // Phase 1 : Generate header page title.
    request.setAttribute(PageTitleTag.HEADER_FOLDER_NAME_KEY, currentFolder.getDocumentName());
    
    // Phase 2 : Generate folder location path.
    int pathDisplayNum = SystemParameterFactory.getSystemParameter(SystemParameterConstant.LOCATION_DISPLAY_NUMBER) != null ? Integer.parseInt(SystemParameterFactory.getSystemParameter(SystemParameterConstant.LOCATION_DISPLAY_NUMBER)) : SystemParameterConstant.DEFAULT_LOCATION_DISPLAY_NUMBER;
    Integer parentFolderID = currentFolder.getParentID();
    int pathCount = 0;
    StringBuffer locationBuffer = new StringBuffer();
    StringBuffer ellipsisBuffer = new StringBuffer();
    StringBuffer rootFolderPathBuffer = new StringBuffer();

    while (parentFolderID.intValue() > 0) {
      pathCount++;
      
      StringBuffer buffer = new StringBuffer();
      DmsDocument document = docRetrievalManager.getDocument(parentFolderID);
      
      if (document.getParentID().intValue() == 0) {
        break;
      }
      
      DmsDocument parentDocument = docRetrievalManager.getDocument(document.getParentID());
      boolean isRootFolder = (DmsDocument.PERSONAL_ROOT_FOLDER_NAME.equals(parentDocument.getDocumentName())) && (parentDocument.getParentID().intValue() == 0) ? true : false;

      buffer.append(pathSeparator);
      buffer.append(
            "<a href=\"" +
                  request.getContextPath() + "/dms/ListDmsDocument.do?" +
                  "rootID=" + document.getRootID() +
                  "&parentID=" + document.getID() +
                  "&curFunctionCode=" + SystemFunctionConstant.DMS_PERSONAL_FOLDER + "&myPage=listDmsDocument" +
                  "\"" +
            ">"
            );
      buffer.append(document.getDocumentName());
      buffer.append("</a>");
      
      if (isRootFolder) {
        rootFolderPathBuffer.insert(0, buffer);
      } else if ((pathDisplayNum > 0) && (pathCount > pathDisplayNum)) {
        ellipsisBuffer.insert(0, buffer);
      } else {
        locationBuffer.insert(0, buffer);
      }
      
      parentFolderID = document.getParentID();
    }
    
    if (!Utility.isEmpty(ellipsisBuffer)) {
      String ellipsisStr = ellipsisBuffer.toString();
      if (ellipsisStr.startsWith(pathSeparator)) {
        ellipsisStr = ellipsisStr.substring((pathSeparator).length());
      }
      
      locationBuffer.insert(0,
          pathSeparator +
          "<span id=\"ellipsisSection\">" +
          "<a " +
            "href=\"#\" " +
            "onmouseover=\"return getDocumentInfo('"
              + TextUtility.escapeJSString(ellipsisStr) +
              "')\" " +
            "onmouseout=\"return nd()\" " +
            "onclick=\"FindObj('ellipsisSection').innerHTML = '"
              + TextUtility.escapeJSString(ellipsisStr) +
              "';nd();return false;\"" +
          ">" +
          "..." +
          "</a>" +
          "</span>"
          );
    }
    
    if (!Utility.isEmpty(rootFolderPathBuffer)) {
      locationBuffer.insert(0, rootFolderPathBuffer);
    }
    
    request.setAttribute(PagePathTag.NAVIGATION_FOLDER_LOCATION_KEY, locationBuffer.toString());
  }
  
  /**
   * Before Entering PERSONAL folder, checking access right. 
   * - for detail, view #EIP-2166.
   * @param form
   * @param request
   * @return true-hasRight; false-hasNotRight.
   * @throws ApplicationException
   */
  private boolean checkPersonalFolderAccessRight(ActionForm form, HttpServletRequest request) throws ApplicationException {
    boolean hasRight = true;
    SessionContainer sessionContainer = this.getSessionContainer(request);

    Connection conn = null;
    DmsDocument dmsDocument = null;
    DmsRoot dmsRoot = null;
    
    Integer userRecordID = sessionContainer.getUserRecordID();
    if(Utility.isEmpty(userRecordID)) {
      return false;
    }
    
    ListDmsDocumentForm docSearchForm = (ListDmsDocumentForm) form;
    try {
      conn = this.getConnection(request);
      DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
      RootOperationManager rootOperationManager = new RootOperationManager(sessionContainer, conn);
      
      dmsDocument = new DmsDocument();
      dmsRoot = new DmsRoot();
      Integer parentID = null;
      Integer rootID = null;
      
      boolean hasRightAccessParent = true;
      boolean hasRightAccessRoot = true;
      
      if(!Utility.isEmpty(docSearchForm.getParentID())) {
        parentID = TextUtility.parseIntegerObj(docSearchForm.getParentID());

        dmsDocument = docRetrievalManager.getDocumentByID(parentID);

        if(dmsDocument == null) {
          return false;
        }
        
        dmsRoot = docRetrievalManager.getDmsRoot(dmsDocument.getRootID());
        
        if(DmsRoot.PERSONAL_ROOT.equals(dmsRoot.getRootType()) && (userRecordID.intValue() != dmsRoot.getOwnerID().intValue())) {
          hasRightAccessParent = false;
        }
      }
      if(!Utility.isEmpty(docSearchForm.getRootID())) {
        rootID = TextUtility.parseIntegerObj(docSearchForm.getRootID());
        
        dmsRoot = docRetrievalManager.getDmsRoot(rootID);
        
        if(dmsRoot == null) {
          return false;
        }
        
        if(DmsRoot.PERSONAL_ROOT.equals(dmsRoot.getRootType()) && (userRecordID.intValue() != dmsRoot.getOwnerID().intValue())) {
          hasRightAccessRoot = false;
        }
      }
      
      hasRight = (hasRightAccessParent && hasRightAccessRoot);
      
      this.commit(request);

      docRetrievalManager.release();
      rootOperationManager.release();

      return hasRight;
    } catch (ApplicationException appEx) {
      this.rollback(request);
      throw appEx;
    } catch (Exception e) {
      log.error("Database Error occur", e);
      this.rollback(request);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
      conn = null;
    }
  }
}